package com.chenxi.vhr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chenxi.vhr.bean.BaseUser;
import com.chenxi.vhr.bean.BaseUserRole;
import com.chenxi.vhr.bean.common.Result;
import com.chenxi.vhr.mapper.BaseUserRoleMapper;
import com.chenxi.vhr.service.BaseUserService;
import com.chenxi.vhr.mapper.BaseUserMapper;
import com.chenxi.vhr.utils.SystemUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 */
@Service
public class BaseUserServiceImpl extends ServiceImpl<BaseUserMapper, BaseUser>
    implements BaseUserService {

    @Autowired
    BaseUserMapper baseUserMapper;

    @Autowired
    BaseUserRoleMapper baseUserRoleMapper;

    @Override
    public List<BaseUser> listWithRole(boolean disCurrentUser, String keywords) {
        BaseUser currentUser = SystemUtil.getCurrentUser();
        return baseUserMapper.listWithRole(disCurrentUser, currentUser.getId(), keywords);
    }
    @Override
    @Transactional
    public boolean userAuthorise(Integer userId, List<Integer> roleIdList) {
        QueryWrapper<BaseUserRole> queryWrapper = new QueryWrapper<BaseUserRole>();
        queryWrapper.eq("user_id", userId);
        Integer count = baseUserRoleMapper.selectCount(queryWrapper);
        if (count > 0) {
            baseUserRoleMapper.delete(queryWrapper);
        }
        roleIdList.forEach(roleId -> {
            BaseUserRole entity = new BaseUserRole();
            entity.setUserId(userId);
            entity.setRoleId(roleId);
            baseUserRoleMapper.insert(entity);
        });
        return true;
    }

    @Override
    @Transactional
    public Result deleteByUserId(Integer userId) {
        QueryWrapper<BaseUserRole> queryWrapper = new QueryWrapper<BaseUserRole>();
        queryWrapper.eq("user_id", userId);
        Integer count = baseUserRoleMapper.selectCount(queryWrapper);
        if (count > 0) {
            return Result.error("删除失败：当前用户关联角色，请取消角色关联！");
        }
        baseUserMapper.deleteById(userId);
        return Result.ok("删除成功！");
    }

    @Override
    public List<BaseUser> getUserListWithOutCurrentUser(Integer loginUserId) {
        QueryWrapper<BaseUser> queryWrapper = new QueryWrapper();
        queryWrapper.ne("id", loginUserId);
        return baseUserMapper.selectList(queryWrapper);
    }
}




